import { Component, OnInit } from '@angular/core';
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../../util/page-subject";
import {ChainService} from "./chain.service";
import {ResponseUtil} from "../../../../util/response-util";
import {Chain} from "./chain";
import {MsgResult} from "../../../../models/msg-result";
import {MsgConstants} from "../../../../constants/constants";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {TableUtil} from "../../../../util/table-util";

declare var $;
declare var moment;

@Component({
  selector: 'app-chain',
  templateUrl: './chain.component.html',
  styleUrls: ['./chain.component.css']
})
export class ChainComponent implements OnInit {
table;
  chain : Chain;
  constructor(
    private pageSubject : PageSubject,
    private dialogService: OneDialogService,
    private responseUtil: ResponseUtil,
    private tableUtil:TableUtil,
    private chainService :ChainService
  ) {
    this.initObject();
  }

  ngOnInit() {
    $(".one-data-loadState").show();
    this.pushPage();
    this.siteButtonData();
    this.exportBtn();
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    let path = new Path("分析报告", "");
    this.pageSubject.pushPage("空气质量同环比分析", "", path);
  }
  /**
   * 实例化对象
   */
  private initObject() {
    this.chain = new Chain(moment().year(),moment().subtract(1,"w").week(),"nationalSite","dayData",moment().year(),moment().subtract(1,"w").week(),moment().year(),false,"周",moment().subtract(1,"d").format("YYYY-MM-DD")+" 00:00:00",moment().format("YYYY-MM-DD")+" 00:00:00");
  }
  chainTableData(){
    this.chainService.getChainData(this.chain).subscribe(
      result => this.responseUtil.success(result,this.chainDataResult),
      message => this.responseUtil.error(message)
    );
  }
  private chainDataResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.chainTableShow(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  chainTableShow =(datas) =>{
    $(".one-data-loadState").hide();
    if(datas==null){
      datas = [];
    }
    $(".one-table-area").html('<table class="table table-striped" id="airQualityChainTable"></table>');
    this.table = this.tableUtil.load("airQualityChainTable",{
      columns: [
        [
          {
            field: 'index',
            title: '排名',
            width:35,
            rowspan: 2,
            valign:"middle"
          }, {
          field: 'siteName',
          title: '站点名称',
          align:"left",
          halign:"center",
          rowspan: 2,
          valign:"middle",
          width:90
        }, {
          field: ' ',
          title: '综合指数',
          colspan: 3,
          align:"right",
          halign:"center",
          width:150
        }, {
          field: ' ',
          title: 'PM10',
          align:"right",
          halign:"center",
          colspan: 3,
          width:150
        }, {
          field: ' ',
          title: 'PM2.5',
          align:"right",
          halign:"center",
          colspan: 3,
          width:150
        }, {
          field: ' ',
          title: 'SO<sub>2</sub>',
          align:"right",
          halign:"center",
          colspan: 3,
          width:150
        }, {
          field: ' ',
          title: 'NO<sub>2</sub>',
          align:"right",
          halign:"center",
          colspan: 3,
          width:150
        }, {
          field: ' ',
          title: 'CO-95',
          align:"right",
          halign:"center",
          colspan: 3,
          width:150
        }, {
          field: ' ',
          title: 'O<sub>3</sub>-8h-90',
          align:"right",
          halign:"center",
          colspan: 3,
          width:150
        }],[
          {
            field: 'compositeValue',
            title: '指数',
            align:"right",
            halign:"center",
            width:50
          },{
            field: 'compositeTBRatio',
            title: '同比',
            formatter:this.judgeData,
            align:"right",
            halign:"center",
            width:50
          },{
            field: 'compositeHBRatio',
            title: '环比',
            formatter:this.judgeData,
            align:"right",
            halign:"center",
            width:50
          }, {
            field: 'pm10',
            title: '浓度',
            align:"right",
            halign:"center",
            width:50
          },{
            field: 'pm10TBRatio',
            title: '同比',
            formatter:this.judgeData,
            align:"right",
            halign:"center",
            width:50
          },{
            field: 'pm10HBRatio',
            title: '环比',
            formatter:this.judgeData,
            align:"right",
            halign:"center",
            width:50
          },{
            field: 'pm25',
            title: '浓度',
            align:"right",
            halign:"center",
            width:50
          },{
            field: 'pm25TBRatio',
            title: '同比',
            formatter:this.judgeData,
            align:"right",
            halign:"center",
            width:50
          },{
            field: 'pm25HBRatio',
            title: '环比',
            formatter:this.judgeData,
            align:"right",
            halign:"center",
            width:50
          },{
            field: 'so2',
            title: '浓度',
            align:"right",
            halign:"center",
            width:50
          },{
            field: 'so2TBRatio',
            title: '同比',
            formatter:this.judgeData,
            align:"right",
            halign:"center",
            width:50
          },{
            field: 'so2HBRatio',
            title: '环比',
            formatter:this.judgeData,
            align:"right",
            halign:"center",
            width:50
          },{
            field: 'no2',
            title: '浓度',
            align:"right",
            halign:"center",
            width:50
          },{
            field: 'no2TBRatio',
            title: '同比',
            formatter:this.judgeData,
            align:"right",
            halign:"center",
            width:50
          },{
            field: 'no2HBRatio',
            title: '环比',
            formatter:this.judgeData,
            align:"right",
            halign:"center",
            width:50
          },{
            field: 'co',
            title: '浓度',
            align:"right",
            halign:"center",
            width:50
          },{
            field: 'coTBRatio',
            title: '同比',
            formatter:this.judgeData,
            align:"right",
            halign:"center",
            width:50
          },{
            field: 'coHBRatio',
            title: '环比',
            formatter:this.judgeData,
            align:"right",
            halign:"center",
            width:50
          },{
            field: 'o3',
            title: '浓度',
            align:"right",
            halign:"center",
            width:50
          },{
            field: 'o3TBRatio',
            title: '同比',
            formatter:this.judgeData,
            align:"right",
            halign:"center",
            width:50
          },{
            field: 'o3HBRatio',
            title: '环比',
            formatter:this.judgeData,
            align:"right",
            halign:"center",
            width:50
          }
        ]
      ],
      data:datas,
      pagination :true,
      paginationLoop: false,
      striped :true,
      paginationPreText : "上一页",
      paginationNextText :"下一页",
      undefinedText : " ",
      height:$(window.innerHeight)[0]-224,
      pageSize:15,
      pageList :[10,15,20]
    });
  }
  //    判断同比环比上升或下降
  private judgeData(value, row, index) {
    if(value){
      if(value>0){
        return '<span class="one-table-riseData">'+value+'</span>';
      }else if(value == "0.00"||value == "-"){
        return '<span>'+value+'</span>';
      }else{
        return '<span class="one-table-declineData">'+value+'</span>';
      }
    }else{
      return '<span>-</span>';
    }
  }


  /**
   * 初始化时间插件
   */
  initTime(){
    let config = {
      timePicker:true,
      timePickerIncrement:5,
      timePicker24Hour:true,
      parentEl:$(".wrapper"),
      locale:{
        format:"YYYY-MM-DD",
        separator: " 至 ",
        applyLabel : '确定',
        cancelLabel : '取消',
        fromLabel: '从',
        toLabel: '到',
        weekLabel: 'W',
        customRangeLabel: 'Custom Range',
        daysOfWeek:["日","一","二","三","四","五","六"],
        monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
        firstDay:1
      },
      startDate: this.chain.startTime,
      endDate: this.chain.endTime,
      maxDate: this.chain.endTime
    };
    $("#chainDate").daterangepicker(config);
  }
  /**
   * 数据类型点击
   */
  clickDataType(type){
    this.chain.dataType = type;
    this.chain.isYearData = type == "yearData" ? true : false;
    let chooseYear = moment().format("YYYY");//$("#chainYear").val();
    this.chain.year = moment().format("YYYY");
    if(type == "monthData"){
      this.chain.weekOrMonthCode = "月";
      this.chain.weekOrMonth = (chooseYear == this.chain.nowYear) ? moment().subtract(1,"M").format("M") : 12;
    }else if(type == "weekData"){
      this.chain.weekOrMonthCode = "周";
      this.chain.weekOrMonth = (chooseYear == this.chain.nowYear) ? moment().subtract(1,"w").subtract(1,"w").week() : 53;
    }else if(type == "yearData"){
      this.chain.year = moment().subtract(1,"y").format("YYYY");
    }
  }
  /**
   * 站点类型点击
   */
  clickPointType(type){
    this.chain.pointType = type;
  }
  /**
   * 日期改变
   */
  changeDate(type){
    let chooseYear = $("#chainYear").val();
    console.log(chooseYear);
    if(chooseYear == this.chain.nowYear){
      if(type=="year"){
        this.chain.dataType == "weekData" && $("#chainDay").val(moment().subtract(1,"w").week());
        this.chain.dataType == "monthData" && $("#chainDay").val(new Date().getMonth()+1);
      }
      this.chain.weekOrMonth = this.chain.dataType == "monthData"?new Date().getMonth()+1 :this.chain.dataType == "weekData"?moment().subtract(1,"w").week():0;
    }else{
      this.chain.weekOrMonth = this.chain.dataType == "monthData"?12 :this.chain.dataType == "weekData"?53:0;
    }
    console.log(this.chain.weekOrMonth);
  }
  /**
   * 查询
   */
  search(){
    this.chain.yearNum = $("#chainYear").val();
    if(this.chain.dataType == "yearData"){
      this.chain.monthOrWeekNum = 0;
    }else{
      this.chain.monthOrWeekNum = $("#chainDay").val();
    }
    this.chain.startTime =$.trim($("#chainDate").val().split("至")[0])+" 00:00:00";
    this.chain.endTime = $.trim($("#chainDate").val().split("至")[1])+" 00:00:00";
    $(".one-data-loadState").show();
    this.chainTableData();
  }
  /**
   * 添加导出按钮
   */
  exportBtn(){
    $(".one-btn-data-type").append("<div class='pull-right'><button class='btn btn-success export'>导出为Excel</button></div>");
    $(".export").click(function(){
      console.log("aa");
      let yearNum = $("#chainYear").val();
      let monthOrWeekNum = $("#chainDay").val();
      console.log(this.chain);
      let baseUrl = location.protocol + "//" + location.host + "/";
      let objString = "yearNum="+yearNum+"&monthOrWeekNum="+monthOrWeekNum+"&pointType="+this.chain.pointType+"&dataType="+this.chain.dataType;
      window.location.href = baseUrl+"api/exportExcel/airQualityContrastRatioExcelExport?format=json&"+objString;
    }.bind(this));
  }


  //站点按钮数据
  siteButtonData(){
    this.chainService.getUserSiteData().subscribe(
      result => this.responseUtil.success(result,this.siteButtonDataResult),
      message => this.responseUtil.error(message)
    );
  }
  private siteButtonDataResult = (result: MsgResult) =>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.siteButtonDataDataTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  //站点按钮
  siteButtonDataDataTree(data){
    let siteHtml = " ";
    let localSite = [
      {"name":"nationalSite","className":"national","type":"national","chinese":"国控站"},
      {"name":"provinceSite","className":"province","type":"province","chinese":"省控站"},
      {"name":"smallAirSite","className":"small","type":"smallAir","chinese":"微型站"}
    ];
    $.each(localSite,function (j,siteList) {
      $.each(data,function (i,list) {
        if(list==siteList.name){
          siteHtml+='<div class="btn btn-default '+siteList.className+'" id="'+siteList.name+'" data-type="national">'+siteList.chinese+'</div>';
        }
      });
    });
    if(siteHtml){
      $(".user_site_button").html(siteHtml);
      $(".user_site_button").find(".btn:first").addClass("active");
      this.chain.pointType = $(".user_site_button").find(".btn:first").attr("id");
      this.initTime();
      this.chainTableData();
      this.siteButtonClick();
    }else{
      $(".one-content").html("暂无数据");
    }

  };
  //点击按钮
  siteButtonClick(){
    $(".user_site_button .btn").click(function (e) {
      $(e.target).addClass("active").siblings(".active").removeClass("active");
      this.chain.pointType = $(e.target).attr("id");
    }.bind(this));
  }

}
